<template>
  <div style="padding-top:46px">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="昵称设置" fixed>
      <van-icon name="arrow-left" slot="left" color="#333" @click="back" />
    </van-nav-bar>
    <div class="content">
      <span class="nickname">昵称</span>
      <input class="nickname_input" type="text" placeholder="仅支持中英文、数字" v-model="memberInfo.nickName">
    </div>
    <button class="confirm_btn"
            :class="memberInfo.nickName === '' ? 'disable' : ''"
            :disabled="memberInfo.nickName === ''"
            @click="updateNickName">
      确认
    </button>
  </div>
</template>

<script type="text/babel">
  import {
    selectBeeUser,
    updateBeeUser
  } from 'services/beeUser';
  import { setToastTimer } from 'framework/utils/utils';
  import { mapGetters } from 'vuex';

  export default {
    name: 'NickName',
    data() {
      return {
        memberInfo: {}
      };
    },
    created() {
      this.fetchData();
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      fetchData() {
        const { userNo } = this.userInfo;

        selectBeeUser({ userNo }).then((response) => {
          this.memberInfo = response.object;
        });
      },
      updateNickName() {
        const { userNo } = this.userInfo;

        const { nickName } = this.memberInfo;

        const nickNameReg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/;

        if (nickNameReg.test(nickName)) {
          updateBeeUser({ userNo, nickName }).then(() => {

            this.$toast({
              message: '修改昵称成功！',
              duration: 1000,
              forbidClick: true
            });

            // 弹窗结束返回
            setToastTimer(() => {
              this.$store.dispatch('refreshUserInfo', this.userInfo);
              this.$router.replace('/message');
            }, 1000);
          });
        } else {
          this.$toast({
            type: 'fail',
            message: '昵称仅支持中英文、数字',
            duration: 1000,
            forbidClick: true
          });
        }
      },
      back() {
        this.$router.go(-1);
      }
    }
  };
</script>

<style lang="less" scoped>
  .content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin: 30px 0 50px 0;
    font-size: 32px;
    height: 90px;
    padding-left: 30px;
    background-color: #ffffff;
    .nickname {
      margin-right: 30px;
    }
    .nickname_input {
      border: none;
    }
  }

  .confirm_btn {
    width: 690px;
    height: 90px;
    border: none;
    border-radius: 50px;
    font-size: 32px;
    background-color: #f7a427;
    color: #ffffff;
    margin-left: 30px;
    &.disable {
      background-color: #fbcb82;
    }
  }
</style>